package com.wxh.order.controller;

import com.netflix.discovery.EurekaClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wxh.order.entity.Order;
import com.wxh.order.entity.User;
import com.wxh.order.feign.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Date;


/**
 * @author wxh
 */
@RestController
public class OrderRibbonController {
    @Autowired
    private EurekaClient eurekaClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${user.url}")
    private String userUrl;

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/user/{userId}")
    public User getUser(@PathVariable Long userId) {
//        InstanceInfo instanceInfo = eurekaClient.getNextServerFromEureka("PROVIDER-USER", false);
        return restTemplate.getForObject("http://PROVIDER-USER/user/" + userId, User.class);
    }

    @GetMapping("/test")
    public String test() {
        // 通过负载均衡的算法查找服务实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("PROVIDER-USER");
        return serviceInstance.getServiceId() + "|" + serviceInstance.getHost() + ":" + serviceInstance.getPort();
    }

    /**
     * 获取用户订单
     *
     * @param userId
     * @return
     */
    @GetMapping("/order/{userId}")
    public Order getOrder(@PathVariable Long userId) {
        // 调用feigin客户端访问user信息
        return newOrder(userFeignClient.getUser(userId));
    }

    /**
     * 获取用户订单
     *
     * @param user
     * @return
     */
    @GetMapping("/order/user")
//    @HystrixCommand(fallbackMethod = "error")
    public Order getOrder(User user) {
        return newOrder(userFeignClient.getUser(user));
    }

    private Order newOrder(User user) {
        Order order = new Order();
        if (user.getUserId() <= 0) {
            order.setSuccess(false);
            order.setMsg("查找用户信息失败！");
            return order;
        }

        order.setUser(user);
        order.setOrderNum("ORD20190131100001");
        order.setOrderName("订购商品");
        order.setOrderDate(new Date());
        return order;
    }

    /**
     * 失败后执行的方法
     *
     * @param user
     * @return
     */
    public Order error(User user) {
        Order order = new Order();
        order.setOrderName("未查询到订单");
        order.setOrderDate(new Date());
        return order;
    }

    @RequestMapping("/home")
    public String home() throws Exception {
        throw new Exception("Sam 错误");
//        throw new MyException("101", "Sam 错误");

    }

}
